package com.lybus.lyxackunimall.db;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlRowSetResultSetExtractor;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 洛阳行数据库服务类
 */
@Service
public class LyxDBService {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    /**
     * 判断电话是否存在
     * @param phone 电话
     * @return
     */
    private boolean existPhone(String phone){
        SqlRowSet query = jdbcTemplate.query("select count(*) from lyx_app.sys_user where login_name = '" + phone + "'",
                new SqlRowSetResultSetExtractor()
        );
        query.next();
        long count = query.getLong(1);
        return count > 0;
    }

    @Transactional
    public void insertUser(String phone, Long mallId, String password, String salt){
        if (existPhone(phone)){
            // 用户存在,直接返回
            return;
        }
        // 注册用户类型  public static final String REGISTER_USER_TYPE = "01";
        String sql = "insert into lyx_app.sys_user(login_name, user_type, phonenumber, password, salt, create_time) values(" +
                "'"+phone+"', '01', '"+phone+"', '"+password+"', '"+salt+"', sysdate())";
        jdbcTemplate.execute(sql);
        jdbcTemplate.execute("insert into lyx_app.unimall_user(id, phone) values("+mallId+", '"+phone+"')");
    }
    @Transactional
    public void updateUser(String phone, Long mallId, String password, String salt) {
        if (!existPhone(phone)){
           insertUser(phone, mallId, password, salt);
        }else {
            SqlRowSet query = jdbcTemplate.query("select user_id from  lyx_app.sys_user where login_name = '" + phone + "'",
                    new SqlRowSetResultSetExtractor());
            query.next();
            long id = query.getLong(1);
            String sql = "update  lyx_app.sys_user set password = '"+password+"', salt = '"+salt+"' where user_id = " + id;
            jdbcTemplate.execute(sql);
        }
    }
}
